package de.lulusoft.anothertorrent.gui.commands;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.IHandlerListener;

import de.lulusoft.anothertorrent.core.rtorrent.Tracker;
import de.lulusoft.anothertorrent.gui.exceptions.ExceptionHandler;

public class TrackerChangeEnabledCommand implements IHandler {
	
	public static final String ID = "de.lulusoft.anothertorrent.gui.commands.TrackerChangeEnabledCommand";
	
	public static final String P_TRACKER = "trackerParameter";
	public static final String P_ENABLED = "enabledParameter";

	@Override
	public void addHandlerListener(IHandlerListener handlerListener) {
	}

	@Override
	public void dispose() {
	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		if (event.getTrigger() instanceof Tracker)
		{
			Tracker t = (Tracker)event.getTrigger();
			Long val = Long.parseLong(event.getParameter(P_ENABLED));
			try {
				// Send cmd to server
				t.getTorrent().getServer().getRTorrentManager().trackerSetEnabled(
						t.getTorrent().getHash(), t.getIndex(), val);
			} catch (Exception e) {
				ExceptionHandler.alert("Could not set trackers enabled state", e);
			}
			
			// Change local cached data to reflect the changes immediately
			t.setEnabled(val);
		}
		return null;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

	@Override
	public boolean isHandled() {
		return true;
	}

	@Override
	public void removeHandlerListener(IHandlerListener handlerListener) {
	}

}
